package org.lex.dbq.model.service;

import java.io.IOException;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
import java.util.Set;

import org.lex.dbq.model.bo.DefaultDriver;
import org.lex.dbq.model.bo.DriverConfig;
import org.lex.dbq.model.bo.JdbcUrlTemplate;
import org.lex.dbq.model.conf.Conf;
import org.lex.dbq.model.conf.ConfLoader;
import org.lex.dbq.model.jdbc.template.JdbcUrlBuilder;

public class TemplateService extends CommonService<JdbcUrlTemplate> {
	private static final TemplateService INSTANCE = new TemplateService();

	public static TemplateService getInstance() {
		return INSTANCE;
	}

	@Override
	public synchronized void store() throws IOException {
		ConfLoader.storeTemplates(Conf.TEMPLATES_CONF_FILE, this.getAllObjects());
	}

	private TemplateService() {
		ConfLoader.loadTemplates(Conf.TEMPLATES_CONF_FILE, this);
		// load system drivers which have template
		log.debug("load system drivers:");
		for (Enumeration<Driver> drivers = DriverManager.getDrivers(); drivers.hasMoreElements();) {
			Driver sysDriver = drivers.nextElement();

			String driverClass = sysDriver.getClass().getName();
			Set<DefaultDriver> set = ServiceFactory.getDefaultDriversService().getDrivers(driverClass);
			if (false == set.isEmpty()) {
				DriverConfig dc = this.findDynamicDriverConfig(driverClass);
				for (DefaultDriver dd : set) {
					this.add(this.create(dd, dc));
				}
			}
		}
	}

	private DriverConfig findDynamicDriverConfig(String driverClass) {
		for (DriverConfig dc : ServiceFactory.getDriverService().getAllObjects()) {
			if (dc.isDynamic() && dc.getClassName().equals(driverClass)) {
				return dc;
			}
		}
		return null;
	}

	private JdbcUrlTemplate create(DefaultDriver dd, DriverConfig dc) {
		JdbcUrlTemplate t = new JdbcUrlTemplate();
		t.setDynamic(true);
		t.setDriver(dc);
		t.setName(dd.getName());
		t.setTemplate(dd.getUrl());
		t.setDescription("Dynamic System Template");
		t.getVariables().addAll(new JdbcUrlBuilder().parseVariables(dd.getUrl()));
		return t;
	}
}
